<template>
  <div id="map" style="map">
    <div >
      <button @click="change_img" class="btn">卫星图</button>
      <button @click="change_vec" class="btn">矢量图</button>
      <button @click="change_ter" class="btn">地形图</button>
      <button @click="startDrawLine" class="btn">测量距离</button>
      <button @click="" class="btn">测量面积</button>
      <button @click="clearDrawLine" class="btn">清除</button>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
//引用supermap的iclient类库
import { TileSuperMapRest } from "@supermap/iclient-ol";
import XYZ from "ol/source/XYZ";
import "ol/ol.css"
import {Vector as VectorLayer} from "ol/layer";
import {Vector as VectorSource} from "ol/source";
import {Circle as CircleStyle, Fill, Stroke, Style} from "ol/style";
import Draw from "ol/interaction/Draw";
import {LineString} from "ol/geom";
import {getArea, getLength} from "ol/sphere";
import Overlay from "ol/Overlay";
import {unByKey} from "ol/Observable";
import {Select} from "ol/interaction";

//超图
var supermap = new TileLayer({
  source: new TileSuperMapRest({
    url: "http://123.56.110.82:8090/iserver/services/map-WYCSSJ0407/rest/maps/WYDLTB",
    wrapX: true,
    transparent:true,
  }),
  zIndex:2000,
  projection: "EPSG:4326"
});

//天地图卫星图片
var map_img = new TileLayer({
  source: new XYZ({
    url:  'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d'
  }),
  zIndex:10,
});
var map_name = new TileLayer({
  source: new XYZ({
    url:  'http://t{0-7}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=406d2b04b58d2d49366047643dcc5f12'
  }),
  zIndex:10,
});

//天地图矢量图
var map_cva= new TileLayer({
  source: new XYZ({
    url: "http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
  }),
  zIndex:10,
});
var map_vec =new TileLayer({
  source: new XYZ({
    url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
  }),
  zIndex:10,
});

//天地图地形图
var map_ter =new TileLayer({
  source: new XYZ({
    url: "http://t4.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
  }),
  zIndex:10,
});
var map_cta =new TileLayer({
  source: new XYZ({
    url:  "http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
  }),
  zIndex:10,
});

export default {
  name: "supermap",
  data(){
    return{
      map: null,
      map_img:null,
      map_name:null,
      map_cva:null,
      map_vec:null,
      map_ter:null,
      map_cta:null,
      raster: null,
      vector: null,
      sketch: null, //当前绘制调整
      helpTooltipElement: null, //提示信息.
      helpTooltip: null, //叠加显示提示信息.
      measureTooltipElement: null, //度量值提示
      measureTooltip: null, //叠加显示测量值.
      continuePolygonMsg: "单击以继续绘制多边形，双击结束绘制 ",
      continueLineMsg: "单击以继续绘制线，双击结束绘制",
      draw: null, //全局删除。
      listener: null
    }
  },

  mounted(){
     this.mapinit();
  },
  methods:{
    //初始化地图
    mapinit(){
      //声明新地图
      this.map = new Map({
        target: "map",
        //controls: control.defaults({ attributionOptions: { collapsed: false } }).extend([new Logo()]),
        view: new View({
          center: [115.87,37.79],
          zoom: 11.5,
          projection: "EPSG:4326",
        })
      });

      //加载天地图和超图
      this.map.addLayer(map_vec);
      this.map.addLayer(map_name);
      this.map.addLayer(supermap);
    },

    //天地图卫星图、天地图标识
    change_img (){
      this.map.removeLayer(map_vec);
      this.map.removeLayer(map_name);
      this.map.addLayer(map_img);
    },
    //显示矢量图
    change_vec(){
      this.map.removeLayer(map_img);
      this.map.addLayer(map_vec);
    },
    //显示地形图
    change_ter(){
      this.map.addLayer(map_ter);
      this.map.addLayer(map_cta);
      this.map.addLayer(supermap);
      // console.log(this.map.getLayers());
    },

    //划线事件
    addMapEvent() {
      this.map.on("pointermove", this.pointerMoveHandler);

      this.map.getViewport().addEventListener("mouseout", () => {
        this.helpTooltipElement.classList.add("hidden");
      });
      this.addInteraction();
    },

    //添加划线交互
    addInteraction() {
      this.draw = new Draw({
        source: this.vector.getSource(),
        type: "LineString",
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)"
          }),
          stroke: new Stroke({
            color: "rgba(0, 0, 0, 0.5)",
            lineDash: [10, 10],
            width: 5
          }),
          image: new CircleStyle({
            radius: 5,
            stroke: new Stroke({
              color: "rgba(0, 0, 0, 0.7)"
            }),
            fill: new Fill({
              color: "rgba(255, 255, 255, 0.2)"
            })
          })
        })
      });

      this.map.addInteraction(this.draw);
      this.createMeasureTooltip();
      this.createHelpTooltip();
      this.drawHandler();
    },



    // 绘制面积




    //开始绘制线
    pointerMoveHandler(evt) {
      if (evt.dragging) {
        return;
      }
      var helpMsg = "点击开始绘制";
      if (this.sketch) {
        var geom = this.sketch.getGeometry();
        if (geom instanceof LineString) {
          helpMsg = this.continueLineMsg;
        }
      }
      this.helpTooltipElement.innerHTML = helpMsg;
      this.helpTooltip.setPosition(evt.coordinate);
      this.helpTooltipElement.classList.remove("hidden");
    },

     // * 格式化划线输出线长.
    formatLength(line) {
      const sourceProj = this.map.getView().getProjection();//获取投影坐标系
      var length = getLength(line,{projection: sourceProj});
      var output;
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + " " + "千米";
      } else {
        output = Math.round(length * 100) / 100 + " " + "米";
      }
      return output;
    },

     // 创建新的长度提示
    createMeasureTooltip() {
      if (this.measureTooltipElement) {
        this.measureTooltipElement.parentNode.removeChild(
            this.measureTooltipElement
        );
      }
      this.measureTooltipElement = document.createElement("div");
      this.measureTooltipElement.className = "ol-tooltip ol-tooltip-measure";
      this.measureTooltip = new Overlay({
        element: this.measureTooltipElement,
        offset: [0, -15],
        positioning: "bottom-center"
      });
      this.map.addOverlay(this.measureTooltip);
    },

     // 创建提示
    createHelpTooltip() {
      if (this.helpTooltipElement) {
        this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement);
      }
      this.helpTooltipElement = document.createElement("div");
      this.helpTooltipElement.className = "ol-tooltip hidden";
      this.helpTooltip = new Overlay({
        element: this.helpTooltipElement,
        offset: [15, 0],
        positioning: "center-left"
      });
      this.map.addOverlay(this.helpTooltip);
    },

    //开始绘制线段
    drawHandler() {
      this.draw.on("drawstart", evt => {
        this.sketch = evt.feature;
        let tooltipCoord = evt.coordinate;

        this.listener = this.sketch.getGeometry().on("change", evt => {
          let output;
          const geom = evt.target;
          if (geom instanceof LineString) {
            output = this.formatLength(geom);
            tooltipCoord = geom.getLastCoordinate();
          }
          this.measureTooltipElement.innerHTML = output;
          this.measureTooltip.setPosition(tooltipCoord);
        });
      });

      this.draw.on("drawend", () => {
        this.measureTooltipElement.className = "ol-tooltip ol-tooltip-static";
        this.measureTooltip.setOffset([0, -7]);
        this.sketch = null;
        this.measureTooltipElement = null;
        this.createMeasureTooltip();
        unByKey(this.listener);
      });
    },
    //绘制线段，并显示长度
    startDrawLine(){
      //初始化矢量图层 用于添加线段点
      this.vector = new VectorLayer({
        source: new VectorSource(),
        zIndex:9999,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 0, 0, 0.8)"
          }),
          stroke: new Stroke({
            color: "#ffcc33",
            width: 5
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "#ffcc33"
            })
          })
        })
      });

      this.map.addLayer(this.vector);
      this.addMapEvent();
    },
    //清除绘制的线段
    clearDrawLine(){
      this.map.getOverlays().clear();//关键点
      this.map.removeLayer(this.vector);
    }
  }
}
</script>

<style scoped>
#map{
  height: 940px;
  width: 1920px;
  border: 2px solid  #ff0000;
}
.map {
  height: 100%;
  /deep/  .ol-tooltip {
    position: relative;
    background: rgba(0, 0, 0, 0.7);
    border-radius: 4px;
    color: white;
    padding: 4px 8px;
    opacity: 0.7;
    white-space: nowrap;
    font-size: 12px;
  }
  /deep/ .ol-tooltip-measure {
    opacity: 1;
    font-weight: bold;
  }
  /deep/  .ol-tooltip-static {
    border: 1px solid #f00;
    background: #f00;
    color: #fff;
    border-radius: 3px;
    padding: 3px;
    margin: 3px;
  }
  /deep/   .ol-tooltip-measure:before,
    /deep/    .ol-tooltip-static:before {
    border-top: 6px solid rgba(0, 0, 0, 0.5);
    border-right: 6px solid transparent;
    border-left: 6px solid transparent;
    content: "";
    position: absolute;
    bottom: -6px;
    margin-left: -7px;
    left: 50%;
  }
  /deep/ .ol-tooltip-static:before {
    border-top-color: #ff0000;
  }
}
</style>
